package com.course.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class DatabaseUtil {
    private static final String DATA_DIR = "data";
    
    static {
        // 确保数据目录存在
        File dir = new File(DATA_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    // 保存对象到文件
    public static <T> void saveToFile(String fileName, List<T> data) {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(DATA_DIR + File.separator + fileName))) {
            oos.writeObject(data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 从文件加载对象
    @SuppressWarnings("unchecked")
    public static <T> List<T> loadFromFile(String fileName) {
        File file = new File(DATA_DIR + File.separator + fileName);
        if (!file.exists()) {
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(file))) {
            return (List<T>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    // 生成新的ID
    public static int generateId(String fileName) {
        List<?> data = loadFromFile(fileName);
        return data.size() + 1;
    }
} 